<template>
  <el-form ref="form" :model="formData" :rules="rulesChgPass" status-icon label-width="100px" class="demo-ruleForm">
    <el-form-item label="原密码" prop="originalPass">
      <el-input v-model="formData.originalPass" type="password" auto-complete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input v-model="formData.pass" type="password" auto-complete="off" />
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input v-model="formData.checkPass" type="password" auto-complete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmitForm('form')">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { changePassword } from '@/api/login'

const formData = {
  originalPass: '',
  pass: '',
  checkPass: ''
}

export default {
  data() {
    const validateOriginalPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入原密码'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 5) {
        callback(new Error('密码长度不能小于5位'))
      } else {
        if (this.formData.checkPass !== '') {
          this.$refs.form.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formData.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      formData: { ...formData },
      rulesChgPass: {
        originalPass: [
          { validator: validateOriginalPass, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          changePassword(this.formData).then(res => {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.formData = { ...formData }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
